//
//  HMOAuthViewController.swift
//  Black22
//
//  Created by Apple on 16/11/21.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import SVProgressHUD

//  微博的唯一id
let AppKey = "932421745"
//  微博的secrect
let Redirect_Uri = "http://www.itcast.cn"
//  秘钥
let AppSecret = "bf49771e565be773d40afb5de317dad0"

//  第三方登录页面
class HMOAuthViewController: UIViewController {

    //  懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    //  自定义视图
    override func loadView() {
        //  不透明，防止底部黑条的出现
        webView.isOpaque = false
        //  设置代理
        webView.delegate = self
        view = webView
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNavUI()
        loadUrl()
    }
    
    
    //  加载url
    private func loadUrl() {
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_Uri)"
        print(url)
        
        let urlRequest = URLRequest(url: URL(string: url)!)
        webView.loadRequest(urlRequest)
    }
    
    
    //  添加导航栏按钮
    private func setupNavUI() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
        navigationItem.title = "微博登录"
    }
    
    // MARK:    --点击事件
    @objc private func cancelAction() {
        
    }
    
    @objc private func autoFillAction() {
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'gtt1078753788@163.com';document.getElementById('passwd').value = 'guoting123'")
    }
    
//    //  根据code获取accesstoken
//    fileprivate func requestAccesstoken(code: String) {
//    
//        HMNetworkTools.sharedTools.requestAccessToken(code: code, callBack: { (response, error) -> Void in
//            if error != nil {
//                print(error!)
//                return
//            }
//            //  代码执行到此获取字典数据
//            let dic = response as! [String: Any]
//            print(dic)
//            let userAccount = HMUserAccount(dic: dic)
//            //  获取用户信息
//            self.requestUserInfo(userAccount: userAccount)
//        })
//    }
//    //  获取用户信息
//    func requestUserInfo(userAccount: HMUserAccount) -> Void {
//        
//        HMNetworkTools.sharedTools.requestUserInfo(accessToken: userAccount.access_token!, uid: userAccount.uid, callBack: { (response, error) -> Void in
//        
//            if error != nil {
//                print(error!)
//                return
//            }
//            //  获取字典数据
//            let dic = response as! [String: Any]
//            //  用户昵称，用户头像
//            //  设置模型数据
//            userAccount.name = dic["name"] as? String
//            userAccount.avatar_large = dic["avatar_large"] as? String
//            
//            //  保存用户数据
//            userAccount.saveUserAccount()
//            
//            
//        })
//        
//        
//        
//    }
    
    
    

   

}



extension HMOAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //  将要开始请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.url else {
            return false
        }
        //  不是我们关心的url，我们放行，让其加载
        if !url.absoluteString.hasPrefix(Redirect_Uri) {
            return true
        }
        
        //  代码执行到此，表示是我们关心的url，截取code，不需要加载 
        if let query = url.query, query.hasPrefix("code=") {
            //  使我们关心的参数,获取code
            let code = query.substring(from: "code=".endIndex)
            
            //  获取accesstoken
            HMUserAccountViewModel.sharedUserAccount.requestAccesstoken(code: code, callBack: { (isSuccess) in
                if isSuccess {
                    //  登录成功
                    print("登录成功")
                    
                    //  当前控制器dismis完成才去切换跟跟视图控制器
                    self.dismiss(animated: false, completion: {
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotificationName), object: self)
                    })
                    
                }
            })
            print(code)
            
        } else {
            //  取消授权的操作
        }
        
        return false
    }
    
}











